
checkLogin()
render()

//渲染所有学生数据
async function nameData() {
    const res = await axios.get('/students')
    console.log(res)
    const html = res.data.map(item => {
        const { name, age, gender, province, city, area, hope_salary, salary, group, id } = item
        return `<tr data-id="${id}">
        <td>${name}</td>
        <td>${age}</td>
        <td>${gender === 0 ? '男' : '女'}</td>
        <td>第${group}组</td>
        <td>${hope_salary}</td>
        <td>${salary}</td>
        <td>${province + city + area}</td>
        <td >
          <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen"></i></a>
          <a href="javascript:;" class="text-danger"><i class="bi bi-trash"></i></a>
        </td>
      </tr>
    `
    }).join('')
    document.querySelector('.list').innerHTML = html
    document.querySelector('.total').innerText = res.data.length
}
nameData()
//显示弹框
const modalDom = document.querySelector('#modal')
const modal = new bootstrap.Modal(modalDom)
document.querySelector('#openModal').addEventListener('click', () => {
    //修改标题
    document.querySelector('.modal-title').innerText = '添加学生'
    //document.querySelector('#form').requestFullscreen()
    //表单重置
    document.querySelector('#form').reset()
    //清空籍贯
    cityData.innerHTML = `  <option value="">--城市--</option>`
    areaData.innerHTML = `  <option value="">--地区--</option>`
    //删除自定义属性
    modalDom.dataset.id = ''
    modal.show()
})
const provinceData = document.querySelector('[name=province]')
const cityData = document.querySelector('[name=city]')
const areaData = document.querySelector('[name=area]')
//渲染省市区
async function getProvinces() {
    const res = await axios.get('/api/province')
    const html = res.list.map(item => {
        return `<option value="${item}">${item}</option>`
    }).join('')
    provinceData.innerHTML = `<option value="">--省份--</option>${html}`
    provinceData.addEventListener('change', async () => {
        const res = await axios.get(`/api/city`, {
            params: {
                pname: provinceData.value
            }
        })
        const html = res.list.map(item => {
            return `<option value="${item}">${item}</option>`
        }).join('')
        cityData.innerHTML = `<option value="">--城市--</option>${html}`
        areaData.innerHTML = `<option value="">--地区--</option>`

    })
    cityData.addEventListener('change', async () => {
        const res = await axios.get(`/api/area`, {
            params: {
                pname: provinceData.value,
                cname: cityData.value
            }
        })
        const html = res.list.map(item => {
            return `<option value="${item}">${item}</option>`
        }).join('')
        areaData.innerHTML = `<option value="">--地区--</option>${html}`
    })

}
getProvinces()

//添加功能


document.querySelector('#openModal').addEventListener('click', function () {
    modal.show()
})

document.querySelector('#submit').addEventListener('click', function () {
    const form = document.querySelector('#form')
    const data = serialize(form, { hash: true, empty: true })
    //非空验证
    if (!data.name || !data.age || !data.gender || !data.group || !data.hope_salary || !data.salary || !data.province || !data.city || !data.area) {
        alert('内容不能为空')
        return
    } else {
        axios({
            url: '/students',
            method: 'POST',

            headers: {

            },
            data: {
                name: data.name,
                age: +data.age,
                gender: +data.gender,
                group: +data.group,
                province: data.province,
                city: data.city,
                area: data.area,
                hope_salary: +data.hope_salary,
                salary: +data.salary

            },
        }).then(res => {
            nameData()
            modal.hide()
        })
    }
    console.log(data);


})
//删除信息

document.querySelector('.list').addEventListener('click', function (e) {
    if (e.target.classList.contains('bi-trash')) {
        const id = e.target.closest('tr').dataset.id   
        console.log(id);
        axios({
            url: `/students/${id}`,
            method: 'DELETE',
            headers: {
                Authorization: localStorage.getItem('my-token')
            },
        }).then(res => {
            nameData(); // 重新渲染学生数据
            alert('删除成功');
        }).catch(err => {
            console.error('删除失败:', err);
            alert('删除失败');
        });

    }
});
// 修改功能
document.querySelector('.list').addEventListener('click', function (e) {
    if (e.target.classList.contains('bi-pen')) {
        const id = e.target.closest('tr').dataset.id 
        if (id) {
            // 获取学生信息
            axios({
                url: `/students/${id}`,
                method: 'GET',
                headers: {
                    Authorization: localStorage.getItem('my-token')
                },
            }).then(res => {
                const student = res.data;
                // 修改标题
                document.querySelector('.modal-title').innerText = '修改学生';
                // 填充表单
                document.querySelector('#form').reset();
                document.querySelector('[name=name]').value = student.name;
                document.querySelector('[name=age]').value = student.age;
                document.querySelector('[name=gender]').value = student.gender;
                document.querySelector('[name=group]').value = student.group;
                document.querySelector('[name=hope_salary]').value = student.hope_salary;
                document.querySelector('[name=salary]').value = student.salary;
                document.querySelector('[name=province]').value = student.province;
                document.querySelector('[name=city]').value = student.city;
                document.querySelector('[name=area]').value = student.area;
                // 设置自定义属性
                modalDom.dataset.id = id;
                modal.show();
            }).catch(err => {
                console.error('获取学生信息失败:', err);
                alert('获取学生信息失败');
            });
        } else {
            alert('无法获取学生ID');
        }
    }
});

// 提交修改后的信息
document.querySelector('#submit').addEventListener('click', function () {
    const form = document.querySelector('#form');
    const data = serialize(form, { hash: true, empty: true });
    // 非空验证
    if (!data.name || !data.age || !data.gender || !data.group || !data.hope_salary || !data.salary || !data.province || !data.city || !data.area) {
        alert('内容不能为空');
        return;
    } else {
        const id = modalDom.dataset.id;
        if (id) {
            axios({
                url: `/students/${id}`,
                method: 'PUT',
                headers: {
                    Authorization: localStorage.getItem('my-token')
                },
                data: {
                    name: data.name,
                    age: +data.age,
                    gender: +data.gender,
                    group: +data.group,
                    province: data.province,
                    city: data.city,
                    area: data.area,
                    hope_salary: +data.hope_salary,
                    salary: +data.salary
                },
            }).then(res => {
                nameData(); // 重新渲染学生数据
                modal.hide();
            }).catch(err => {
                console.error('修改失败:', err);
                alert('修改失败');
            });
        } else {
            alert('无法获取学生ID');
        }
    }
    console.log(data);
});